package com.joker.aigc.chat.service.event.listener;


import com.joker.aigc.domain.entity.User;
import com.joker.aigc.domain.enums.WebSocketChatActiveStatusEnum;
import com.joker.aigc.chat.service.SocketService;
import com.joker.aigc.service.UserService;
import com.joker.aigc.chat.service.adapter.WebSocketAdapter;
import com.joker.aigc.chat.service.event.UserOfflineEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 用户下线监听器
 *
 * @author zhongzb create on 2022/08/26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UserOfflineListener {

    private final SocketService webSocketService;
    private final UserService userService;


    @Async
    @EventListener(classes = UserOfflineEvent.class)
    public void saveRedisAndPush(UserOfflineEvent event) {
        User user = event.getUser();
        // 移除redis 缓存信息
        userService.offline(user.getId(), user.getLastOptTime());
        //推送给所有在线用户，该用户下线
        webSocketService.sendToAllOnline(WebSocketAdapter.buildOfflineNotifyResp(event.getUser()), event.getUser().getId());
    }

    @Async
    @EventListener(classes = UserOfflineEvent.class)
    public void saveDB(UserOfflineEvent event) {
        // 下线准备
        User user = event.getUser();
        User update = new User();
        update.setId(user.getId());
        update.setLastOptTime(user.getLastOptTime());
        update.setActiveStatus(WebSocketChatActiveStatusEnum.OFFLINE.getStatus());
        userService.updateById(update);
    }

}
